
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Demo," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>模型高级特性，引入模型关联关系 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        模型高级特性，引入模型关联关系
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:36.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Demo/" rel="tag">Ember-Demo</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 11 分钟</span>
    </header>

    <div class="post-content">
      <p>来源：<a target="_blank" rel="noopener" href="http://yoember.com/">yoember.com</a><br>作者：<a target="_blank" rel="noopener" href="http://zoltan.nz/">Zoltan</a></p>
<p><strong>声明</strong>：<em>本文的转载与翻译是经过作者认可的，再次感谢原作，如有侵权请给我留言，我会删除博文！！</em> 希望本系列教程能帮助更多学习Ember.js的初学者。</p>
<p>接着前面五篇：</p>
<ol>
<li><a href="http://xcoding.tech/2016/03/30/Ember-Demo/%E7%8E%AF%E5%A2%83%E6%90%AD%E5%BB%BA%E4%BB%A5%E5%8F%8A%E4%BD%BF%E7%94%A8Ember.js%E5%88%9B%E5%BB%BA%E7%AC%AC%E4%B8%80%E4%B8%AA%E9%9D%99%E6%80%81%E9%A1%B5%E9%9D%A2/">环境搭建以及使用Ember.js创建第一个静态页面</a></li>
<li><a href="http://xcoding.tech/2016/03/31/Ember-Demo/%E5%BC%95%E5%85%A5%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E3%80%81action%E3%80%81%E5%8A%A8%E6%80%81%E5%86%85%E5%AE%B9/">引入计算属性、action、动态内容</a></li>
<li><a href="http://xcoding.tech/2016/03/31/Ember-Demo/%E6%A8%A1%E5%9E%8B%EF%BC%8C%E4%BF%9D%E5%AD%98%E6%95%B0%E6%8D%AE%E5%88%B0%E6%95%B0%E6%8D%AE%E5%BA%93/">模型，保存数据到数据库</a></li>
<li><a href="http://xcoding.tech/2016/03/31/Ember-Demo/%E5%8F%91%E5%B8%83%E9%A1%B9%E7%9B%AE%EF%BC%8C%E5%8A%A0%E5%85%A5CRUD%E5%8A%9F%E8%83%BD/">发布项目，加入CRUD功能</a></li>
<li><a href="http://xcoding.tech/2016/03/31/Ember-Demo/%E4%BB%8E%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%8E%B7%E5%8F%96%E6%95%B0%E6%8D%AE%EF%BC%8C%E5%BC%95%E5%85%A5%E7%BB%84%E4%BB%B6/">从服务器获取数据，引入组件</a></li>
</ol>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>本篇主要是介绍模型直接的关联关系，比如：一对一、一对多关系。会创建两个模型<code>author</code>和<code>book</code>，设置它们的关系，并增加测试数据。</p>
<h2 id="创建模型并设置关联"><a href="#创建模型并设置关联" class="headerlink" title="创建模型并设置关联"></a>创建模型并设置关联</h2><p>关联关系设置API：</p>
<ol>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/data/#method_belongsTo">belongsTo</a></li>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/data/#method_hasMany">hasMany</a></li>
</ol>
<p><strong>模型关系</strong>：一个<code>library</code>对应多个<code>book</code>，一个<code>author</code>对应多个<code>book</code>。关系图如下：</p>
<p><img src="/image/blog-image/180.png" alt="library模型关系图"></p>
<p>使用<a target="_blank" rel="noopener" href="http://ember-cli.com/user/guide">Ember CLI</a>命令创建模型。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ember g model book title:string releaseYear:date library:belongsTo author:belongsTo</span><br><span class="line">ember g model author name:string books:hasMany</span><br></pre></td></tr></table></figure>
<p>手动在<code>library</code>中增加<code>hasMany</code>关联关系。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> Model <span class="keyword">from</span> <span class="string">&#x27;ember-data/model&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> attr <span class="keyword">from</span> <span class="string">&#x27;ember-data/attr&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; hasMany &#125; <span class="keyword">from</span> <span class="string">&#x27;ember-data/relationships&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Model.extend(&#123;</span><br><span class="line">  name: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">  address: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">  phone: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line"></span><br><span class="line">  books: hasMany(<span class="string">&#x27;books&#x27;</span>),</span><br><span class="line"></span><br><span class="line">  isValid: Ember.computed.notEmpty(<span class="string">&#x27;name&#x27;</span>),</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="创建一个后台管理页面“Seeder”"><a href="#创建一个后台管理页面“Seeder”" class="headerlink" title="创建一个后台管理页面“Seeder”"></a>创建一个后台管理页面“Seeder”</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ember g route admin&#x2F;seeder</span><br></pre></td></tr></table></figure>
<p>检查<code>router.js</code>看看路由是否成功创建。相关代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//  其他代码不变，省略</span></span><br><span class="line"><span class="built_in">this</span>.route(<span class="string">&#x27;admin&#x27;</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;invitations&#x27;</span>);</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;contacts&#x27;</span>);</span><br><span class="line">    <span class="built_in">this</span>.route(<span class="string">&#x27;seeder&#x27;</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//  其他代码不变，省略</span></span><br></pre></td></tr></table></figure>
<p>修改导航模板<code>navbar.hbs</code>增加新建路由的入口链接。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">ul</span> <span class="attr">class</span>=<span class="string">&quot;dropdown-menu&quot;</span>&gt;</span></span><br><span class="line">  &#123;&#123;#nav-link-to &#x27;admin.invitations&#x27;&#125;&#125;Invitations&#123;&#123;/nav-link-to&#125;&#125;</span><br><span class="line">  &#123;&#123;#nav-link-to &#x27;admin.contacts&#x27;&#125;&#125;Contacts&#123;&#123;/nav-link-to&#125;&#125;</span><br><span class="line">  &#123;&#123;#nav-link-to &#x27;admin.seeder&#x27;&#125;&#125;Seeder&#123;&#123;/nav-link-to&#125;&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="使用Ember-RSVP-hash-在一个路由中返回多个模型的数据"><a href="#使用Ember-RSVP-hash-在一个路由中返回多个模型的数据" class="headerlink" title="使用Ember.RSVP.hash()在一个路由中返回多个模型的数据"></a>使用<code>Ember.RSVP.hash()</code>在一个路由中返回多个模型的数据</h2><p><a target="_blank" rel="noopener" href="http://emberjs.com/">Ember</a>支持在一个路由的<code>model</code>回调中返回多个模型的数据。有关方法发API请看<a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/RSVP.html#method_hash">Ember.RSVP.hash()</a>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/routes/admin/seeder.js</span></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line"></span><br><span class="line">  model() &#123;</span><br><span class="line">    <span class="keyword">return</span> Ember.RSVP.hash(&#123;</span><br><span class="line">      libraries: <span class="built_in">this</span>.store.findAll(<span class="string">&#x27;library&#x27;</span>),</span><br><span class="line">      books: <span class="built_in">this</span>.store.findAll(<span class="string">&#x27;book&#x27;</span>),</span><br><span class="line">      authors: <span class="built_in">this</span>.store.findAll(<span class="string">&#x27;author&#x27;</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  setupController(controller, model) &#123;</span><br><span class="line">    controller.set(<span class="string">&#x27;libraries&#x27;</span>, model.libraries);</span><br><span class="line">    controller.set(<span class="string">&#x27;books&#x27;</span>, model.books);</span><br><span class="line">    controller.set(<span class="string">&#x27;authors&#x27;</span>, model.authors);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上述<code>model()</code>回调中返回了三个模型的数据：<code>library</code>、<code>book</code>和<code>author</code>。需要注意的是：上述代码中方法<code>Ember.RSVP.hash()</code>会发送3个请求，并且只有三个请求都成功才会执行成功。<br>在<code>setupController()</code>回调中，把三个模型分别设置到<code>controller</code>中。</p>
<h2 id="路由内置方法调用次序"><a href="#路由内置方法调用次序" class="headerlink" title="路由内置方法调用次序"></a>路由内置方法调用次序</h2><p>每个路由内都内置了很多方法，比如前面介绍的<code>model</code>、<code>setupController</code>、<code>renderTemplate</code>，这些都是内置在路由类中的方法，那么这些方法调用次序又是如何的呢？请看下面的代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/routes/test.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line"></span><br><span class="line">  init() &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  beforeModel(transition) &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  model(params, transition) &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  afterModel(model, transition) &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  activate() &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  setupController(controller, model) &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  renderTemplate(controller, model) &#123;</span><br><span class="line">    <span class="keyword">debugger</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>打开浏览器的debug模式并在执行到这个路由中<a target="_blank" rel="noopener" href="http://localhost:4200/test">http://localhost:4200/test</a>。可以看到方法的执行次序与上述代码方法的次序是一致的。有关API请看下面网址的介绍：</p>
<ol>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/Ember.Route.html#method_init">init()</a></li>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/Ember.Route.html#method_beforeModel">beforeModel(transition)</a></li>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/Ember.Route.html#method_model">model(params, transition)</a></li>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/Ember.Route.html#method_activate">activate()</a></li>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/Ember.Route.html#method_setupController">setupController(controller, model)</a></li>
<li><a target="_blank" rel="noopener" href="http://emberjs.com/api/classes/Ember.Route.html#method_renderTemplate">renderTemplate(controller, model)</a></li>
</ol>
<h2 id="数量显示功能"><a href="#数量显示功能" class="headerlink" title="数量显示功能"></a>数量显示功能</h2><p>创建一个组件用于显示各个模型数据的总数。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ember g component number-box</span><br></pre></td></tr></table></figure>
<p>组件创建完毕之后在组件类中增加css类，使用属性<code>classNames</code>设置。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/components/number-box.js</span></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Component.extend(&#123;</span><br><span class="line"></span><br><span class="line">  classNames: [<span class="string">&#x27;panel&#x27;</span>, <span class="string">&#x27;panel-warning&#x27;</span>]</span><br><span class="line"></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>然后在组件模板中增加代码：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/components/number-box.hbs --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;panel-heading&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">h3</span> <span class="attr">class</span>=<span class="string">&quot;text-center&quot;</span>&gt;</span>&#123;&#123;title&#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">h1</span> <span class="attr">class</span>=<span class="string">&quot;text-center&quot;</span>&gt;</span>&#123;&#123;if number number &#x27;...&#x27;&#125;&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>在修改<code>app/templates/admin/seeder.hbs</code></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/admin/seeder.hbs --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>Seeder, our Data Center<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;row&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4&quot;</span>&gt;</span>&#123;&#123;number-box title=&quot;Libraries&quot; number=libraries.length&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4&quot;</span>&gt;</span>&#123;&#123;number-box title=&quot;Authors&quot; number=authors.length&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4&quot;</span>&gt;</span>&#123;&#123;number-box title=&quot;Books&quot; number=books.length&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>等待项目重启完成，进入到后台的seeder下可以看到三个小圆点，请记得，一定要在<code>setupController</code>中设置数据，<code>model</code>回调会自动从服务器获取数据，<code>obj.length</code>意思是调用<code>length()</code>方法获取数据长度，然后直接显示到模板上，效果如下截图，由于后面两个模型还没有数据所以显示省略号。</p>
<p><img src="/image/blog-image/184.png" alt="结果截图"></p>
<h2 id="构建表单生成测试数据"><a href="#构建表单生成测试数据" class="headerlink" title="构建表单生成测试数据"></a>构建表单生成测试数据</h2><p>前面已经介绍过属性的传递，下面的代码将为读者介绍一些更加高级的东西！！一大波代码即将来临！！！</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">ember g component seeder-block</span><br><span class="line">ember g component fader-label</span><br></pre></td></tr></table></figure>

<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">// app/components/seeder-block.js</span><br><span class="line">import Ember from &#x27;ember&#x27;;</span><br><span class="line"></span><br><span class="line">export default Ember.Component.extend(&#123;</span><br><span class="line"></span><br><span class="line">  actions: &#123;</span><br><span class="line">    generateAction() &#123;</span><br><span class="line">      this.sendAction(&#x27;generateAction&#x27;);</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    deleteAction() &#123;</span><br><span class="line">      this.sendAction(&#x27;deleteAction&#x27;);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/components/seeder-block.hbs --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;row&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-12&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h3</span>&gt;</span>&#123;&#123;sectionTitle&#125;&#125;<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;row&quot;</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;form-horizontal&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">label</span> <span class="attr">class</span>=<span class="string">&quot;col-sm-2 control-label&quot;</span>&gt;</span>Number of new records:<span class="tag">&lt;/<span class="name">label</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-sm-2&quot;</span>&gt;</span></span><br><span class="line">          &#123;&#123;input value=counter class=&#x27;form-control&#x27;&#125;&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-sm-4&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;btn btn-primary&quot;</span> &#123;&#123;<span class="attr">action</span> &#x27;<span class="attr">generateAction</span>&#x27;&#125;&#125;&gt;</span>Generate &#123;&#123;sectionTitle&#125;&#125;<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">          &#123;&#123;#fader-label isShowing=createReady&#125;&#125;Created!&#123;&#123;/fader-label&#125;&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-sm-4&quot;</span>&gt;</span></span><br><span class="line">          <span class="tag">&lt;<span class="name">button</span> <span class="attr">class</span>=<span class="string">&quot;btn btn-danger&quot;</span> &#123;&#123;<span class="attr">action</span> &#x27;<span class="attr">deleteAction</span>&#x27;&#125;&#125;&gt;</span>Delete All &#123;&#123;sectionTitle&#125;&#125;<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">          &#123;&#123;#fader-label isShowing=deleteReady&#125;&#125;Deleted!&#123;&#123;/fader-label&#125;&#125;</span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">// app/components/fader-label.js</span><br><span class="line">import Ember from &#x27;ember&#x27;;</span><br><span class="line"></span><br><span class="line">export default Ember.Component.extend(&#123;</span><br><span class="line">  tagName: &#x27;span&#x27;,</span><br><span class="line"></span><br><span class="line">  classNames: [&#x27;label label-success label-fade&#x27;],</span><br><span class="line">  classNameBindings: [&#x27;isShowing:label-show&#x27;],</span><br><span class="line"></span><br><span class="line">  isShowing: false,</span><br><span class="line"></span><br><span class="line">  isShowingChanged: Ember.observer(&#x27;isShowing&#x27;, function() &#123;</span><br><span class="line">    Ember.run.later(() =&gt; &#123;</span><br><span class="line">      this.set(&#x27;isShowing&#x27;, false);</span><br><span class="line">    &#125;, 3000);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>代码<code> classNames: [&#39;label label-success label-fade&#39;]</code>的作用是绑定三个CSS类到标签<code>span</code>上，得到html如<code>&lt;span class=&quot;label label-success label-fade&quot;&gt;xxx&lt;/span&gt;</code>。<br>代码<code>classNameBindings: [&#39;isShowing:label-show&#39;]</code>的作用是根据属性<code>isShowing</code>的值判断是否添加CSS类<code>label-show</code>到标签<code>span</code>上。更多有关信息请看<a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/03/21/ember-js-ru-men-zhi-nan-zhi-shi-er-handlebarsshu-xing-bang-ding/">Ember.js 入门指南之十二handlebars属性绑定</a></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/components/fader-label.hbs --&gt;</span></span><br><span class="line">&#123;&#123;yield&#125;&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">// app/styles/app.scss</span><br><span class="line"><span class="keyword">@import</span> <span class="string">&#x27;bootstrap&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">body</span> &#123;</span><br><span class="line">  <span class="attribute">padding-top</span>: <span class="number">20px</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-tag">html</span> &#123;</span><br><span class="line">  <span class="attribute">overflow-y</span>: scroll;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.library-item</span> &#123;</span><br><span class="line">  <span class="attribute">min-height</span>: <span class="number">150px</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.label-fade</span> &#123;</span><br><span class="line">  <span class="attribute">opacity</span>: <span class="number">0</span>;</span><br><span class="line">  @include transition(all 0.5s);</span><br><span class="line">  &amp;<span class="selector-class">.label-show</span> &#123;</span><br><span class="line">    <span class="attribute">opacity</span>: <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最主要、最关键的部分来了。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- app/templates/admin/seeder.hbs --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>Seeder, our Data Center<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;row&quot;</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4&quot;</span>&gt;</span>&#123;&#123;number-box title=&quot;Libraries&quot; number=libraries.length&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4&quot;</span>&gt;</span>&#123;&#123;number-box title=&quot;Authors&quot; number=authors.length&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;col-md-4&quot;</span>&gt;</span>&#123;&#123;number-box title=&quot;Books&quot; number=books.length&#125;&#125;<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"></span><br><span class="line">&#123;&#123;seeder-block</span><br><span class="line">    sectionTitle=&#x27;Libraries&#x27;</span><br><span class="line">    counter=librariesCounter</span><br><span class="line">    generateAction=&#x27;generateLibraries&#x27;</span><br><span class="line">    deleteAction=&#x27;deleteLibraries&#x27;</span><br><span class="line">    createReady=libDone</span><br><span class="line">    deleteReady=libDelDone</span><br><span class="line">&#125;&#125;</span><br><span class="line"></span><br><span class="line">&#123;&#123;seeder-block</span><br><span class="line">  sectionTitle=&#x27;Authors with Books&#x27;</span><br><span class="line">  counter=authorCounter</span><br><span class="line">  generateAction=&#x27;generateBooksAndAuthors&#x27;</span><br><span class="line">  deleteAction=&#x27;deleteBooksAndAuthors&#x27;</span><br><span class="line">  createReady=authDone</span><br><span class="line">  deleteReady=authDelDone</span><br><span class="line">&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>属性<code>generateAction</code>和<code>deleteAction</code>用于关联控制器中的<code>action</code>方法，属性<code>createReady</code>和<code>deleteReady</code>是标记属性。</p>
<p>等待项目重启完毕，页面结果如下：</p>
<p><img src="/image/blog-image/185.png" alt="result"></p>
<p>底部的两个输入框用于获取生成的数据条数。</p>
<h2 id="安装faker-js构建测试数据"><a href="#安装faker-js构建测试数据" class="headerlink" title="安装faker.js构建测试数据"></a>安装<code>faker.js</code>构建测试数据</h2><p>使用<a target="_blank" rel="noopener" href="https://github.com/johnotander/ember-faker">faker.js</a>构建测试数据。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ember install ember-faker</span><br></pre></td></tr></table></figure>
<p>安装完毕之后扩展各个模型，并在模型中调用<code>randomize()</code>方法产生数据。下面是各个模型的代码。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/models/library.js</span></span><br><span class="line"><span class="keyword">import</span> Model <span class="keyword">from</span> <span class="string">&#x27;ember-data/model&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> attr <span class="keyword">from</span> <span class="string">&#x27;ember-data/attr&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; hasMany &#125; <span class="keyword">from</span> <span class="string">&#x27;ember-data/relationships&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Faker <span class="keyword">from</span> <span class="string">&#x27;faker&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Model.extend(&#123;</span><br><span class="line">  name: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">  address: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">  phone: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line"></span><br><span class="line">  books: hasMany(<span class="string">&#x27;book&#x27;</span>, &#123;<span class="attr">inverse</span>: <span class="string">&#x27;library&#x27;</span>, <span class="attr">async</span>: <span class="literal">true</span>&#125;),</span><br><span class="line"></span><br><span class="line">  isValid: Ember.computed.notEmpty(<span class="string">&#x27;name&#x27;</span>),</span><br><span class="line"></span><br><span class="line">  randomize() &#123;</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;name&#x27;</span>, Faker.company.companyName() + <span class="string">&#x27; Library&#x27;</span>);</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;address&#x27;</span>, <span class="built_in">this</span>._fullAddress());</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;phone&#x27;</span>, Faker.phone.phoneNumber());</span><br><span class="line"></span><br><span class="line">    <span class="comment">// If you would like to use in chain.</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  _fullAddress() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;Faker.address.streetAddress()&#125;</span>, <span class="subst">$&#123;Faker.address.city()&#125;</span>`</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/models/book.js</span></span><br><span class="line"><span class="keyword">import</span> Model <span class="keyword">from</span> <span class="string">&#x27;ember-data/model&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> attr <span class="keyword">from</span> <span class="string">&#x27;ember-data/attr&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; belongsTo &#125; <span class="keyword">from</span> <span class="string">&#x27;ember-data/relationships&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Faker <span class="keyword">from</span> <span class="string">&#x27;faker&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Model.extend(&#123;</span><br><span class="line"></span><br><span class="line">  title:        attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line">  releaseYear:  attr(<span class="string">&#x27;date&#x27;</span>),</span><br><span class="line"></span><br><span class="line">  author:       belongsTo(<span class="string">&#x27;author&#x27;</span>, &#123;<span class="attr">inverse</span>: <span class="string">&#x27;books&#x27;</span>, <span class="attr">async</span>: <span class="literal">true</span>&#125;),</span><br><span class="line">  library:      belongsTo(<span class="string">&#x27;library&#x27;</span>, &#123;<span class="attr">inverse</span>: <span class="string">&#x27;books&#x27;</span>, <span class="attr">async</span>: <span class="literal">true</span>&#125;),</span><br><span class="line"></span><br><span class="line">  randomize(author, library) &#123;</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;title&#x27;</span>, <span class="built_in">this</span>._bookTitle());</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;author&#x27;</span>, author);</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;releaseYear&#x27;</span>, <span class="built_in">this</span>._randomYear());</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;library&#x27;</span>, library);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  _bookTitle() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">`<span class="subst">$&#123;Faker.commerce.productName()&#125;</span> Cookbook`</span>;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  _randomYear() &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="built_in">this</span>._getRandomArbitrary(<span class="number">1900</span>, <span class="number">2015</span>));</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  _getRandomArbitrary(min, max) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Math</span>.random() * (max - min) + min;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/models/author.js</span></span><br><span class="line"><span class="keyword">import</span> Model <span class="keyword">from</span> <span class="string">&#x27;ember-data/model&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> attr <span class="keyword">from</span> <span class="string">&#x27;ember-data/attr&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; hasMany &#125; <span class="keyword">from</span> <span class="string">&#x27;ember-data/relationships&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Faker <span class="keyword">from</span> <span class="string">&#x27;faker&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Model.extend(&#123;</span><br><span class="line"></span><br><span class="line">  name: attr(<span class="string">&#x27;string&#x27;</span>),</span><br><span class="line"></span><br><span class="line">  books: hasMany(<span class="string">&#x27;book&#x27;</span>, &#123;<span class="attr">inverse</span>: <span class="string">&#x27;author&#x27;</span>, <span class="attr">async</span>: <span class="literal">true</span>&#125;),</span><br><span class="line"></span><br><span class="line">  randomize() &#123;</span><br><span class="line">    <span class="built_in">this</span>.set(<span class="string">&#x27;name&#x27;</span>, Faker.name.findName());</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>上述代码中。 <code>async</code>设置为<code>true</code>的作用是：在获取book的同时会把关联的<code>author</code>也加载出来，默认是不加载（延迟加载）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/controllers/admin/seeder.js</span></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> Faker <span class="keyword">from</span> <span class="string">&#x27;faker&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line"></span><br><span class="line">  libraries: [],</span><br><span class="line">  books: [],</span><br><span class="line">  authors: [],</span><br><span class="line"></span><br><span class="line">  actions: &#123;</span><br><span class="line"></span><br><span class="line">    generateLibraries() &#123;</span><br><span class="line">      <span class="keyword">const</span> counter = <span class="built_in">parseInt</span>(<span class="built_in">this</span>.get(<span class="string">&#x27;librariesCounter&#x27;</span>));</span><br><span class="line"></span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; counter; i++) &#123;</span><br><span class="line">        <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;library&#x27;</span>).randomize().save().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">          <span class="keyword">if</span> (i === counter<span class="number">-1</span>) &#123;</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;librariesCounter&#x27;</span>, <span class="number">0</span>);</span><br><span class="line">            <span class="built_in">this</span>.set(<span class="string">&#x27;libDone&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    deleteLibraries() &#123;</span><br><span class="line">      <span class="built_in">this</span>._destroyAll(<span class="built_in">this</span>.get(<span class="string">&#x27;libraries&#x27;</span>));</span><br><span class="line"></span><br><span class="line">      <span class="built_in">this</span>.set(<span class="string">&#x27;libDelDone&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    generateBooksAndAuthors() &#123;</span><br><span class="line">      <span class="keyword">const</span> counter = <span class="built_in">parseInt</span>(<span class="built_in">this</span>.get(<span class="string">&#x27;authorCounter&#x27;</span>));</span><br><span class="line"></span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; counter; i++) &#123;</span><br><span class="line">        <span class="keyword">let</span> newAuthor = <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;author&#x27;</span>);</span><br><span class="line">        newAuthor.randomize()</span><br><span class="line">          .save().then(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">             <span class="keyword">if</span> (i === counter<span class="number">-1</span>) &#123;</span><br><span class="line">               <span class="built_in">this</span>.set(<span class="string">&#x27;authorCounter&#x27;</span>, <span class="number">0</span>);</span><br><span class="line">               <span class="built_in">this</span>.set(<span class="string">&#x27;authDone&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line">             &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        );</span><br><span class="line"></span><br><span class="line">        <span class="built_in">this</span>._generateSomeBooks(newAuthor);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    deleteBooksAndAuthors() &#123;</span><br><span class="line">      <span class="built_in">this</span>._destroyAll(<span class="built_in">this</span>.get(<span class="string">&#x27;books&#x27;</span>));</span><br><span class="line">      <span class="built_in">this</span>._destroyAll(<span class="built_in">this</span>.get(<span class="string">&#x27;authors&#x27;</span>));</span><br><span class="line"></span><br><span class="line">      <span class="built_in">this</span>.set(<span class="string">&#x27;authDelDone&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// Private methods</span></span><br><span class="line"></span><br><span class="line">  _generateSomeBooks(author) &#123;</span><br><span class="line">    <span class="keyword">const</span> bookCounter = Faker.random.number(<span class="number">10</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> j = <span class="number">0</span>; j &lt; bookCounter; j++) &#123;</span><br><span class="line">      <span class="keyword">const</span> library = <span class="built_in">this</span>._selectRandomLibrary();</span><br><span class="line">      <span class="built_in">this</span>.store.createRecord(<span class="string">&#x27;book&#x27;</span>)</span><br><span class="line">        .randomize(author, library)</span><br><span class="line">        .save();</span><br><span class="line">      author.save();</span><br><span class="line">      library.save();</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  _selectRandomLibrary() &#123;</span><br><span class="line">    <span class="keyword">const</span> libraries = <span class="built_in">this</span>.get(<span class="string">&#x27;libraries&#x27;</span>);</span><br><span class="line">    <span class="keyword">const</span> librariesCounter = libraries.get(<span class="string">&#x27;length&#x27;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// Create a new array from IDs</span></span><br><span class="line">    <span class="keyword">const</span> libraryIds = libraries.map(<span class="function">(<span class="params">lib</span>) =&gt;</span> &#123;<span class="keyword">return</span> lib.get(<span class="string">&#x27;id&#x27;</span>);&#125;);</span><br><span class="line">    <span class="keyword">const</span> randomNumber = Faker.random.number(librariesCounter<span class="number">-1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">const</span> randomLibrary = libraries.findBy(<span class="string">&#x27;id&#x27;</span>, libraryIds[randomNumber]);</span><br><span class="line">    <span class="keyword">return</span> randomLibrary;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  _destroyAll(records) &#123;</span><br><span class="line">    records.forEach(<span class="function">(<span class="params">item</span>) =&gt;</span> &#123;</span><br><span class="line">      item.destroyRecord();</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>重启项目，进入到<a target="_blank" rel="noopener" href="http://localhost:4200/admin/seeder">http://localhost:4200/admin/seeder</a>。在输入框内输入要生成的测试数据条数，然后点击右边的蓝色按钮，如果生成成功可以在按钮右边看到绿色的“created”提示文字。如下图：</p>
<p><img src="/image/blog-image/186.png" alt="生成成功"></p>
<p>然后到firebase上查看。可以看到数据已经存在了，并且是随机的数据。</p>
<p><img src="/image/blog-image/187.png" alt="firebase数据截图1"></p>
<p><img src="/image/blog-image/188.png" alt="firebase数据截图2"></p>
<p>并且是实现了数据表之间的关联关系，比如一个<code>author</code>对应多个<code>book</code>，如下图。</p>
<p><img src="/image/blog-image/189.png" alt="author一对多book"></p>
<p>或者是直接在<a target="_blank" rel="noopener" href="http://localhost:4200/libraries">http://localhost:4200/libraries</a>下查看。</p>
<p>在接下来的一篇文章中将介绍如何遍历关联关系中的对象，使用起来也是非常简单的，直接使用面向对象的方式遍历即可。</p>
<h2 id="家庭作业"><a href="#家庭作业" class="headerlink" title="家庭作业"></a>家庭作业</h2><p>本篇的家庭作业仍然是好好理解组件！参照下面的文章认真学习、理解组件。</p>
<ol>
<li><a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/04/07/ember-js-ru-men-zhi-nan-zhi-er-shi-ba-zu-jian-ding-yi/">Ember.js 入门指南之二十八组件定义</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/04/07/ember-js-ru-men-zhi-nan-zhi-er-shi-jiu-shu-xing-chuan-di/">Ember.js 入门指南之二十九属性传递</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/04/07/ember-js-ru-men-zhi-nan-zhi-san-shi-bao-guo-nei-rong/">Ember.js 入门指南之三十包裹内容</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/04/07/ember-js-ru-men-zhi-nan-zhi-san-shi-zi-ding-yi-bao-guo-zu-jian-de-htmlbiao-qian/">Ember.js 入门指南之三十一自定义包裹组件的HTML标签</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/04/07/chu-li-shi-jian/">Ember.js 入门指南之三十二处理事件</a></li>
<li><a target="_blank" rel="noopener" href="http://blog.ddlisting.com/2016/04/07/action-chong-fa-bian-hua-2/">Ember.js 入门指南之三十三action触发变化</a></li>
</ol>
<br>
为了照顾懒人我把完整的代码放在[GitHub](https://github.com/ubuntuvim/library-app)上，如有需要请可以拿来参照参照。博文经过多次修改，博文上的代码与github代码可能有出入，不过影响不大！如果你觉得博文对你有点用，请在github项目上给我点个`star`吧。您的肯定对我来说是最大的动力！！

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/Ember-Demo/%E5%BC%95%E5%85%A5%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E3%80%81action%E3%80%81%E5%8A%A8%E6%80%81%E5%86%85%E5%AE%B9/" rel="prev" title="引入计算属性、action、动态内容">
            引入计算属性、action、动态内容
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E6%A8%A1%E5%9E%8B%E5%B9%B6%E8%AE%BE%E7%BD%AE%E5%85%B3%E8%81%94"><span class="toc-text">创建模型并设置关联</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E5%90%8E%E5%8F%B0%E7%AE%A1%E7%90%86%E9%A1%B5%E9%9D%A2%E2%80%9CSeeder%E2%80%9D"><span class="toc-text">创建一个后台管理页面“Seeder”</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Ember-RSVP-hash-%E5%9C%A8%E4%B8%80%E4%B8%AA%E8%B7%AF%E7%94%B1%E4%B8%AD%E8%BF%94%E5%9B%9E%E5%A4%9A%E4%B8%AA%E6%A8%A1%E5%9E%8B%E7%9A%84%E6%95%B0%E6%8D%AE"><span class="toc-text">使用Ember.RSVP.hash()在一个路由中返回多个模型的数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B7%AF%E7%94%B1%E5%86%85%E7%BD%AE%E6%96%B9%E6%B3%95%E8%B0%83%E7%94%A8%E6%AC%A1%E5%BA%8F"><span class="toc-text">路由内置方法调用次序</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E9%87%8F%E6%98%BE%E7%A4%BA%E5%8A%9F%E8%83%BD"><span class="toc-text">数量显示功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9E%84%E5%BB%BA%E8%A1%A8%E5%8D%95%E7%94%9F%E6%88%90%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE"><span class="toc-text">构建表单生成测试数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%89%E8%A3%85faker-js%E6%9E%84%E5%BB%BA%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE"><span class="toc-text">安装faker.js构建测试数据</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%B6%E5%BA%AD%E4%BD%9C%E4%B8%9A"><span class="toc-text">家庭作业</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '模型高级特性，引入模型关联关系', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
